package com.young.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.young.common.execption.ServiceException;
import com.young.manager.mapper.CompanyMapper;
import com.young.manager.mapper.CompanyUserMapper;
import com.young.manager.model.Company;
import com.young.manager.model.CompanyUser;
import com.young.manager.service.CompanyService;
import java.util.Date;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Slf4j
@RequiredArgsConstructor
@Service
public class CompanyServiceImpl implements CompanyService {

  private final CompanyMapper companyMapper;
  private final CompanyUserMapper companyUserMapper;

  @Override
  public Page<Company> queryPage(String name, String principalPhone, Integer pageNum, Integer pageSize) {
    QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
    if (StringUtils.hasLength(name)) queryWrapper.like("name", name);
    if (StringUtils.hasLength(principalPhone)) queryWrapper.like("principal_phone", principalPhone);
    queryWrapper.orderByDesc("modify_time");
    Page<Company> page = new Page<>(pageNum, pageSize);
    return companyMapper.selectPage(page, queryWrapper);
  }

  @Override
  public void insertCompany(Company company) {
    company.setCreateTime(new Date());
    company.setModifyTime(company.getCreateTime());
    companyMapper.insert(company);
  }

  @Override
  public void updateCompany(Company company) {
    if (null == company.getId()) {
      throw new ServiceException("参数缺失[id]！");
    }
    company.setModifyTime(new Date());
    companyMapper.updateById(company);
  }

  @Override
  public void updateCompanyStatus(Long id, Integer status) {
    UpdateWrapper<Company> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("id", id);
    updateWrapper.set("status", status);
    companyMapper.update(updateWrapper);
    if (status.equals(9)) {
      UpdateWrapper<CompanyUser> companyUserUpdateWrapper = new UpdateWrapper<>();
      companyUserUpdateWrapper.eq("company_id", id);
      companyUserUpdateWrapper.set("status", status);
      companyUserMapper.update(companyUserUpdateWrapper);
    }
  }

  @Override
  public void deleteCompany(Long id) {
    companyMapper.deleteById(id);
  }
}
